/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-6-4 下午5:21 Created by lyyang
 */
package com.xunton.bss.weixin.api.message.event.impl;

import java.util.Date;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import com.xunton.bss.weixin.api.message.event.Event;
import com.xunton.bss.weixin.api.message.event.EventDao;
import com.xunton.bss.weixin.api.message.event.coupon.CouponEvent;

/**
 * 事件dao,jpa实现
 *
 * @author <a href="mailto:lyyang@ceno.cn">lyyang</a>
 * @version 1.0 15-6-4 下午5:21
 */
@Named ("weixin_eventDao")
public class JpaEventDao implements EventDao
{
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    public void save(Event event){
        entityManager.persist(event);
    }

    public PagingList<CouponEvent> query(Criteria criteria)
    {
        String sql = "SELECT entity FROM CouponEvent entity";
        return SqlUtils.sqlQuery(sql,entityManager,criteria);
    }

    public long statCouponCount(long id, String type, Date beginDate, Date endDate)
    {
        String sql = "SELECT count(couponEvent) FROM CouponEvent couponEvent WHERE createTime>=:beginDate and createTime<:endDate and id=:id and event=:type";
        Query query = entityManager.createQuery(sql);
        query.setParameter("beginDate",beginDate);
        query.setParameter("endDate",endDate);
        query.setParameter("id",id);
        query.setParameter("type",type);
        Long result = (Long)query.getSingleResult();
        if(result!=null)
            return result.longValue();
        else
            return 0;
    }

    public long statShakeUvCount(String eventType)
    {
        String sql = "SELECT count(DISTINCT fromUserName) FROM CommonEvent WHERE event=:eventType";
        Query query = entityManager.createQuery(sql);
        query.setParameter("eventType",eventType);
        Object object = query.getSingleResult();
        if(object!=null)
            return (Long)object;
        else
            return 0;
    }
}
